package com.cs171.market.service;

import com.cs171.market.entity.Catogery;
import com.cs171.market.mapper.CategoryMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Endy
 * @create 2020 - 06 - 21 - 0:46
 * @date 2020/6/21 - 0:46
 */

@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 获取所有分类
     */
    public List<Catogery> queryCatList()
    {
        List<Catogery> data = categoryMapper.findAllCategory();
        List<Catogery> catogeryList = new ArrayList<>();
        for(Catogery catogery : data)
        {
            if(catogery.getCat_pid() == 0)
            {
                catogeryList.add(catogery);
            }
        }
        for(Catogery catogery : catogeryList)
        {
            catogery.setChildren(getChild(catogery.getCat_id(), data));
        }
        return catogeryList;
    }

    private List<Catogery> getChild(Integer id, List<Catogery> rootList)
    {
        List<Catogery> childList = new ArrayList<>();
        for(Catogery catogery : rootList)
        {
            if (catogery.getCat_pid().equals(id))
            {
                childList.add(catogery);
            }
        }
        for (Catogery catogery : childList)
        {
            catogery.setChildren(getChild(catogery.getCat_id(), rootList));
        }
        if (childList.size() == 0)
        {
            return null;
        }
        return childList;
    }

    /**
     * 获取所有分类
     */
    public List<Catogery> queryPageCatList(Integer pagenum, Integer pagesize)
    {
        PageHelper.startPage(pagenum, pagesize);
        List<Catogery> catogeryPageList = new ArrayList<>();
        Page<Catogery> data = categoryMapper.findPageCategory();
        for(Catogery catogery : data)
        {
            if(catogery.getCat_pid() == 0)
            {
                catogeryPageList.add(catogery);
            }
        }
        for(Catogery catogery : catogeryPageList)
        {
            catogery.setChildren(getChild(catogery.getCat_id(), data));
        }
        return catogeryPageList;
    }


}
